package com.bwie.auth.consumer;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.remote.UserRemoteService;
import com.bwie.common.domain.Log;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Log4j2
public class RabbitMqConsumer {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserRemoteService userRemoteService;

    @RabbitListener(queuesToDeclare = @Queue("success_queue"))
    public void rabbitMqConsumer(Log login, Message message, Channel channel){
        log.info("消费者接收到消息，消息内容：{}，开始消费：............", JSONObject.toJSONString(login));
        //拿到 每个消息 对应的 唯一标识 id
        String messageId = message.getMessageProperties().getMessageId();
        try {
            Long count = redisTemplate.opsForSet().add("count", messageId);
            if (count!=null&&count==1){
                userRemoteService.addLog(login);
                //手动确认
                // 第一个参数： 消息 的投递序号 自增的数字  根据这个唯一的消息投递序号获取这条消息
                // multiple: 是否支持批量确认
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        } catch (Exception e) {
            redisTemplate.opsForSet().remove("count", messageId);
            log.error("消费者获取到了消息，消息内容：{}，消费失败，异常信息：{}", JSONObject.toJSONString(login), e);
            try {
                //第二个参数是：是否回退到原来的队列  true
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException ex) {
                log.error("消费者获取到了消息，消息内容：{}，消费回退失败，异常信息：{}", JSONObject.toJSONString(login), ex);
            }
        }
    }
}
